package com.yuntian.controller;

import com.yuntian.dto.OrderForm;
import com.yuntian.entity.ProductMaster;
import com.yuntian.entity.SupplierMaster;
import com.yuntian.service.ProductService;
import com.yuntian.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 発注書作成页面控制器
 */
@Controller
@RequestMapping("/PR30101")
public class PR30101Controller {

    private final SupplierService supplierService;
    @Autowired
    private ProductService productService;

    @Autowired
    public PR30101Controller(SupplierService supplierService) {
        this.supplierService = supplierService;
    }

    /**
     * 显示発注書作成页面
     */
    @GetMapping
    public String showOrderPage(Model model) {
        // 查询供应商列表
        List<SupplierMaster> supplierList = supplierService.getAllSuppliers();
        model.addAttribute("supplierList", supplierList);

        // 查询商品列表
        List<ProductMaster> productList = productService.getAllProducts();
        model.addAttribute("productList", productList);

        // 初始化订单表单
        model.addAttribute("orderForm", new OrderForm());

        // 当前登录用户
        model.addAttribute("loginUser", "张毅");

        return "PR30101";
    }

    /**
     * 处理発注書提交
     */
    @PostMapping
    public String submitOrder(OrderForm orderForm, Model model) {
        try {
            model.addAttribute("message", "発注書が正常に作成されました。");
        } catch (Exception e) {
            model.addAttribute("error", "発注書作成失敗: " + e.getMessage());
        }
        model.addAttribute("supplierList", supplierService.getAllSuppliers());
        return "PR30101";
    }
    @PostMapping("/issue")
    public String handleIssue(@ModelAttribute OrderForm orderForm,
                              @RequestParam("kotosi") String year,
                              @RequestParam("gathu") String month,
                              @RequestParam("niti") String day,
                              RedirectAttributes redirectAttributes) {

        // 获取选中的商品明细
        List<ProductMaster> selectedProducts = orderForm.getSelectedProductCodes().stream()
                .map(code -> productService.getProductByCode(code))
                .collect(Collectors.toList());

        // 添加Flash属性（自动传递到重定向页面）
        redirectAttributes.addFlashAttribute("supplierCode", orderForm.getShiiresakiCode());
        redirectAttributes.addFlashAttribute("orderForm", orderForm);
                   orderForm.setShiiresakiName(supplierService.selectNameByCode(orderForm.getShiiresakiCode()));

        redirectAttributes.addFlashAttribute("supplierName", orderForm.getShiiresakiName());
        redirectAttributes.addFlashAttribute("selectedProducts", selectedProducts);

        // 日期格式化处理
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        redirectAttributes.addFlashAttribute("formattedDateNow", LocalDate.now().format(formatter));

        //随机生成5位
        String randomCode = String.format("%05d",new Random().nextInt(100000)) ;
        redirectAttributes.addFlashAttribute("randomCode", randomCode);
        redirectAttributes.addFlashAttribute("formattedDate", year + "年" + month + "月" + day + "日");
        return "redirect:/PR30103"; // 重定向到新地址
    }



}